import { useEffect, useRef, useState } from "react";

function ClickDemo() {
  const [counter, setCounter] = useState(0);
  const [visible, setVisible] = useState(true);
  const outerRef = useRef();
  useEffect(() => {
    const handleClick = (e) => {
      console.log("document click");
      setCounter((c) => c + 1);
    };
		const handleOuterClick = (e) => {
			console.log("outer click");
			setCounter((c) => c + 1);
      // setVisible(false);
		}
    const handleContainerClick = (e) => {
      console.log("root click");
      setCounter((c) => c + 1);
    };
    document.addEventListener("click", handleClick);
    document.querySelector("#root").addEventListener("click", handleContainerClick);
		outerRef.current.addEventListener("click", handleOuterClick);
    return () => {
      console.log("remove event");
      document.removeEventListener("click", handleClick);
      document.querySelector("#root").removeEventListener("click", handleContainerClick);
			outerRef.current.removeEventListener("click", handleOuterClick);
    };
  }, []);
  return (
    <>
      <div id="outer" ref={outerRef}>
        Counter: {counter}
        <div className="ontextmenu" style={{display:visible ? 'block' : 'none'}}>
          <div
            className="item"
            onClick={(e) => {
              console.log("item1 click, current counter:", counter);
            }}
          >
            菜单项1
          </div>
          <div
            className="item"
            onClick={(e) => {
              console.log("item2 click, current counter:", counter);
            }}
          >
            菜单项2
          </div>  
        </div>
      </div>

      <div style={{marginTop:'200px'}}>
        新版本react将按钮绑定的onClick事件放在了#root上，所以点击菜单项时，如控制台所展示的那样
      </div>
    </>
  );
}

export default ClickDemo;
